/**
 * 
 */
package com.library_manager.sverlet.book;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.library_manager.book.Book;
import com.libray_manager.dao.BookDao;

/**
 * @author luolisheng
 *
 */
public class BookDeleteServlet  extends HttpServlet{

	private static final long serialVersionUID = 1L;
	// 书籍Dao对象
	BookDao dao = null;

	/**
	 * 初始化方法
	 * 
	 * 将初始化dao对象的操作放入init()方法,可保证dao只被创建一次
	 */
	@Override
	public void init() throws ServletException {
		// 初始化书籍Dao对象
		dao = new BookDao();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 设置请求编码集为utf-8(避免中文乱码)
		request.setCharacterEncoding("utf-8");
		
		// 创建书籍数据视图对象(用于封装新增书籍信息的数据)
		Book bookParams = new Book();

		// 从页面获取新增数据
		
		bookParams.setBookid(request.getParameter("bookid"));
	
		try {
			// 调用dao中的新增书籍信息方法
			dao.deleteBook(bookParams);
			
			// 将新增结果保存到request对象中(该提示信息会显示在JSP页面中的 <div id='msgs'>${messages}</div>处)
			request.setAttribute("messages", "删除成功!");
			
			// 调用查询书籍列表的Servlet,再次显示新增该书籍后的书籍信息列表
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/bookQuery");
			// 请求转发给书籍信息列表Servlet(/studentQuery)
			rd.forward(request, response);
			
		} catch (Exception e) {
			// 控制台输出异常信息
			e.printStackTrace();
			
			// 将新增结果保存到request对象中(该提示信息会显示在JSP页面中的 <div id='msgs'>${messages}</div>处)
			request.setAttribute("messages", "删除书籍失败!");
			
			// 返回新增书籍信息页面，重新填写书籍信息
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/booklist.jsp");
			// 请求转发给新增书籍信息页面(/jsp/student/studentAdd.jsp)
			rd.forward(request, response);
		}
	}
	}
